#!/bin/bash

start(){
    SERVER_NAME=ctp4j
    OLD_PID=$(jps -v | grep app.name=${SERVER_NAME} | awk '{print $1}')
    echo "already existing PID=${OLD_PID}"
    if [ "X${OLD_PID}" != "X" ]; then
        kill -9 ${OLD_PID}
    fi
    nohup java "-Dapp.name=${SERVER_NAME}" "-Dspring.profiles.active=prd" "-Djasypt.encryptor.password=YWJjMTIzCg==" -jar app.jar > nohup.out 2>&1 &

    COUNT=0
    while [ $COUNT -lt 1 ]; do
        echo "Waiting..."
        sleep 1
        COUNT=$(jps -v | grep app.name=${SERVER_NAME} | awk '{print $1}' | wc -l)
        if [ $COUNT -gt 0 ]; then
            break
        fi
    done

    echo "${SERVER_NAME} is started."
    NEW_PID=$(jps -v | grep app.name=${SERVER_NAME} | awk '{print $1}')
    echo "running PID: ${NEW_PID}"
}

stop(){
    SERVER_NAME=ctp4j
    PID=$(jps -v | grep app.name=${SERVER_NAME} | awk '{print $1}')
    echo "running PID=${PID}"
    if [ "X${PID}" != "X" ]; then
        kill -9 ${PID}
    fi
    echo "${SERVER_NAME} is stoped."
}

main() {
    if [ "$1" = "start" ]; then
        start
    elif [ "$1" = "stop" ]; then
        stop
    elif [ "$1" = "restart" ]; then
        stop
        sleep 5
        start
    else
        echo -e "\033[31m Invalid parameter \033[0m"
    fi
}

main $@

